<template>
  <div>
    <!-- 车辆信息 -->
    <div class="card-wrap flex-column justify-end card-padding">
      <el-form :model="form" ref="cartMessage" label-width="180px" :label-position="type == 'detail' ? 'right' : 'top'" :disabled="type == 'detail'">
        <div class="card-title-wrap">
          <span>{{ $route.query.type == "2" ? "车辆信息" : "车型信息" }}</span>
          <span></span>
        </div>
        <div :style="{ marginLeft: type == 'detail' ? '' : '50px' }">
          <el-table :loading="loading" :data="dataListTable" ref="multipleTable" border @selection-change="handleSelectionChange">
            <!-- 普通列插槽 -->
            <template v-if="$route.query.type == '2'">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="车牌号" align="center">
                <template slot-scope="scope">
                  <span style="color: #3280fc; cursor: pointer" @click="digLogDetail(scope.row)">
                    {{ scope.row.carPlateNo }}</span>
                </template>
              </el-table-column>
              <el-table-column label="车架号" align="center" prop="carVinNo" />
              <el-table-column label="品牌" align="center" prop="carBrandName" />
              <el-table-column label="车系" align="center" prop="carSeriesName" />
              <el-table-column label="车型" align="center" prop="carModelName" min-width="100px" show-overflow-tooltip />
              <el-table-column label="车辆状态" align="center" prop="carStatusStr" />
              <el-table-column label="所属城市" align="center" prop="carLicenseCityVal" />
              <el-table-column label="当前里程/km" align="center" prop="carMileage" />
            </template>

            <template v-else>
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="品牌" align="center">
                <template slot-scope="scope">
                  <span style="color: #3280fc; cursor: pointer" @click="digLogDetail(scope.row)">
                    {{ scope.row.carBrandName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="车系" align="center" prop="carSeriesName" />
              <el-table-column label="车型" align="center" prop="carModelName" min-width="100px" show-overflow-tooltip />
              <el-table-column label="能源类型" align="center" prop="carPowerTypeStr" />
              <el-table-column label="颜色" align="center" prop="appearanceColor" />
              <el-table-column label="每期租金(元)" align="center" prop="planRent" />
              <el-table-column label="租期(月)" align="center" prop="planTenancyTypeStr" />
              <el-table-column label="加装费(元)" align="center" prop="attachedDecorationAmount" />
              <el-table-column label="其他费用" align="center" prop="otherFeeAmount" />
              <el-table-column label="登记性质" align="center" prop="operationTypeStr" />
              <el-table-column label="批过数量" align="center" prop="quantityApproved" />
              <el-table-column label="未下单数量" align="center" prop="quantitySurplus" />
              <el-table-column label="下单数量" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.quantityOrder" placeholder="请输入" @input="placeOrder(scope.row, scope)"></el-input>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
      </el-form>
    </div>
    <el-dialog title="信息" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
      <Details v-model="formData" state="readonly" type="preview"></Details>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { orderPrePlanDetail } from "@/api/vehicleOrder";
import Details from "@/views/quota/forecast/chunk/details/index.vue";
import * as apis from "@/api/quota/forecast/edit/api.js";
export default {
  name: "cartMessage",
  dicts: ["ven_dee"],
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
  },
  components: {
    Details,
  },
  computed: {
    form: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            that.$emit("input", { ...target, [key]: value });
            return true;
          },
        });
        return proxy;
      },
    },
    type() {
      let status;
      switch (this.state) {
        case "write":
          status = "edit";
          break;
        case "disabled":
          status = "detail";
          break;
        case "readonly":
          status = "detail";
          break;
        case "detail":
          status = "detail";
          break;
        case "edit":
          status = "edit";
        case "add":
          status = "add";
          break;
      }
      return status;
    },
  },
  created() {
    this.orderPrePlanDetail();
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      multipleSelection: [],
      dataListTable: [],
      total: 0,
      formData: {},
    };
  },
  methods: {
    initData(calcSchemeId) {
      apis?.Details(calcSchemeId)
        .then((res) => {
          if (res.code == 200) {
            this.formData = res.data;
          }
        })
        .finally(() => { });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    placeOrder(row, scope) {
      console.log(row.quantityOrder);
      if (Number(row?.quantityOrder) > Number(row?.quantitySurplus)) {
        this.$message.error(
          `下单数量不能大于未下单数量,下单数量最大为${Number(
            row.quantitySurplus
          )}`
        );
        this.dataListTable[scope.$index].quantityOrder = 0;
      } else if (this.multipleSelection.length > 0) {
        this.multipleSelection[scope.$index].quantityOrder =
          row.quantityOrder;
        this.form.orderPlanList = this.multipleSelection;
      }
    },
    async orderPrePlanDetail() {
      this.loading = true;
      let params = {
        preOrderId: this.$route.query?.preOrderId,
        orderId: this.$route.query?.orderId,
      };
      try {
        this.loading = false;
        let res = await orderPrePlanDetail(params);
        this.dataListTable = res;
        localStorage.setItem('planTenancyTypeStr', res[0]?.planTenancyTypeStr)
        // 默认回显多选框
        if (
          this.$route.query.beFrom !== "PlaceOrderView" &&
          this.type !== "2"
        ) {
          let newArray = res.filter((v) => {
            return (
              v.quantityOrder !== null && v.quantityOrder !== 0
            );
          });
          this.multipleSelection = newArray;
          this.$nextTick(() => {
            this.dataListTable.forEach((v) => {
              newArray.forEach((j) => {
                if (
                  j.quantityOrder !== null &&
                  j.quantityOrder !== 0
                ) {
                  this.$refs.multipleTable.toggleRowSelection(
                    v,
                    true
                  );
                }
              });
            });
          });
        } else if (
          this.$route.query.beFrom !== "PlaceOrderView" &&
          this.type == "2"
        ) {
          let newArray = res.filter((v) => {
            return v.quantityOrder == 1;
          });
          this.multipleSelection = newArray;
          this.$nextTick(() => {
            this.dataListTable.forEach((v) => {
              newArray.forEach((j) => {
                if (j.quantityOrder == 1) {
                  this.$refs.multipleTable.toggleRowSelection(
                    v,
                    true
                  );
                }
              });
            });
          });
        }
      } catch (error) { }
    },
    digLogDetail(row) {
      if (this.$route.query.type == "2") {
        console.log("car", "车辆");
        this.dialogVisible = true;
        this.initData(row.calcSchemeId);
      } else {
        console.log("vehicleType", "车型");
        this.dialogVisible = true;
        this.initData(row.calcSchemeId);
      }
    },
    // 全选字段
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => {
        return {
          orderPlanId: item.orderPlanId,
          preOrderPlanId: item.preOrderPlanId,
          quantityOrder:
            this.$route.query.type == "2" ? 1 : item.quantityOrder,
        };
      });
      this.form.orderPlanList = this.multipleSelection;
    },
    valid() {
      return new Promise(async (resolve) => {
        let result = true;
        let refs = Object.values(this.$refs);
        for (let index = 0; index < refs?.length; index++) {
          const ref = refs[index];
          if (
            Object.prototype.toString.call(ref) == "[object Array]"
          ) {
            for (let i = 0; i < ref.length; i++) {
              const element = ref[i];
              if (element?.valid) {
                let rc = await element?.valid?.();
                result = result && rc;
              }
              if (element?.validate) {
                let rf = await this._valid(ref);
                result = result && rf;
              }
              if (element?.form_validate) {
                let rf = await this._valid(
                  ref,
                  "form_validate"
                );
                result = result && rf;
              }
            }
          } else {
            if (ref?.valid) {
              let rc = await ref?.valid?.();
              result = result && rc;
            }
            if (ref?.validate) {
              let rf = await this._valid(ref);
              result = result && rf;
            }
            if (ref?.form_validate) {
              let rf = await this._valid(ref, "form_validate");
              result = result && rf;
            }
          }
        }
        resolve(result);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  width: 100%;
  .title {
    border-left: 3px solid #3280fc;
    padding-left: 5px;
    box-sizing: border-box;
  }
}
.app-container {
  background-color: #fff;
}
</style>
